package com.ctrip.corp.obt.shard.sql.parser.forbidden;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.inner.UpdateForbiddenProcessPlugin.MessageContainer;

/**
 * 对update语句中set字段判断是否禁止更新的Composite
 *
 * @author xukang zhang
 * @date 2023/8/16 13:35
 */
public class UpdateForbiddenMatcherComposite {

    private final List<UpdateForbiddenMatcher> updateForbiddenMatcherList = new ArrayList<>();

    public boolean match(String propertyName, Object propertyValue, Object parameterObject, String columnName, MessageContainer messageContainer) {
        for (UpdateForbiddenMatcher updateForbiddenMatcher : updateForbiddenMatcherList) {
            if (updateForbiddenMatcher.match(propertyName, propertyValue, parameterObject, columnName)) {
                TreeSet<String> forbiddenMatcherNameSet = messageContainer.getForbiddenMatcherNameSet();
                if (forbiddenMatcherNameSet == null) {
                    forbiddenMatcherNameSet = new TreeSet<>();
                    messageContainer.setForbiddenMatcherNameSet(forbiddenMatcherNameSet);
                }
                forbiddenMatcherNameSet.add(updateForbiddenMatcher.name());
                return true;
            }
            if (updateForbiddenMatcher.skip(propertyName, propertyValue, parameterObject, columnName)) {
                return false;
            }
        }
        return false;
    }

    /**
     * 注册UpdateForbiddenMatcher
     *
     * @param updateForbiddenMatcher
     */
    public void add(UpdateForbiddenMatcher updateForbiddenMatcher) {
        if (updateForbiddenMatcher != null) {
            this.updateForbiddenMatcherList.add(updateForbiddenMatcher);
        }
    }

    /**
     * 取消注册UpdateForbiddenMatcher
     *
     * @param updateForbiddenMatcher
     */
    public void remove(UpdateForbiddenMatcher updateForbiddenMatcher) {
        if (updateForbiddenMatcher != null) {
            this.updateForbiddenMatcherList.remove(updateForbiddenMatcher);
        }
    }

    /**
     * sort UpdateForbiddenMatcher by order
     */
    public void sort() {
        this.updateForbiddenMatcherList.sort(Comparator.comparingInt(UpdateForbiddenMatcher::order));
    }
}
